/* eslint-disable no-param-reassign */
import { userDictsStore } from '@/store';
import { getDicts } from '@/service/api/system/dict/data';

const dicts = userDictsStore();
/**
 * @description: 获取字典值
 * @params key 字典的查询字段
 * @params parentOptionsKey 页面上的承载字段
 * @params childKey 页面上的承载字段
 * @params callback 回调函数，会将此次的请求传递过去（部分页面需要）
 *
 * ** 使用此方法时，需要将 dictItem 类型定义也引入
 *
 * eg:
 * const dicts = reactive<any>({
    sexOptions: []
   })

   getDictionary('sys_user_sex', dicts, 'sexOptions')
 */
export type dictItem = {
  dictValue: string;
  dictLabel: string;
};
export const getDictionary = (key: string, parentOptionsKey?: object, childKey?: string, callback?: any) => {
  // 如果 pinia 中能拿到，就直接返回
  const keyDict = dicts.getStoreDict(key);
  if (keyDict) {
    if (childKey && parentOptionsKey) {
      (parentOptionsKey as any)[childKey] = keyDict;
    }
    if (callback) callback(keyDict);

    return Promise.resolve(keyDict);
  }

  // 拿不到再进行接口请求
  return new Promise((resolve, reject) => {
    getDicts(key)
      ?.then(r => {
        const d = r.data && r.data.map((i: any) => ({ value: String(i.dictValue), label: i.dictLabel }));

        // 更新 pinia
        if (d) dicts.updateDicts({ [key]: d });

        // eslint-disable-next-line no-param-reassign
        if (childKey && parentOptionsKey) {
          (parentOptionsKey as any)[childKey] = d;
        } else resolve(d);
        if (callback) callback(d);
      })
      .catch(err => {
        reject(err);
      });
  });
};

function getMultLabel(value: string, list: Record<string, any>[]) {
  const _value = value.split(',') || [];
  const _item: any = [];
  list.forEach(i => {
    if (_value.includes(i.value)) _item.push(i.label || i.title);
  });

  return _item.join();
}

/**
 * @description: 用于反显字典类型的值
 * @param {string|number} key 当前值 value
 * @param {*} options 需要匹配的字典值
 * @return {*} 返回对应的 label值 或空
 */
export const formatterDicts = (key: string | number, options: any[]) => {
  const valIsString = typeof key === 'string';
  let item = '';

  if (valIsString && key.indexOf(',') > -1) {
    item = getMultLabel(key, options);
  } else {
    const row = options.find((i: any) => i.value === key);
    item = row ? row.label || row.title : key;
  }
  return item;
};
